// pages/search/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    goodsList: [],
    //输入框的值
    inputValue: "",

    //历史记录
    historyList: []
  },

  onShow:function(){
    let historyList = wx.getStorageSync('history') || [];
    this.setData({historyList})
  },

  

  //定时器ID
  timerId: -1,

  //inputchange事件
  searchInput(e){
   
    clearTimeout(this.timerId);
    console.log("inputchange事件",e);
 
    let { value } = e.detail;
    value = value.trim();//去掉空格
  
    if(!value){
      this.setData({
        goodsList: []
      })
      return;
    }
   
    this.timerId = setTimeout(()=>{
      this.getGoodsList(value)
    },1000)
  },

 
  getGoodsList: async function (queryValue) {
    //历史记录
    let {historyList} = this.data;
    let index = historyList.findIndex(item=>item === queryValue);
    if(index === -1) historyList.push(queryValue)
    let { data } = await wx.goodsApi.getGoodsList({query:queryValue});
    console.log("data",data);
    this.setData({
      goodsList: data.message,
      historyList
    });
    wx.setStorageSync('history', historyList)
  },

  //点击取消按钮事件
  onSearchCal(){
    this.setData({
      goodsList: [],
      inputValue: ""
    })
  },

  //清空历史记录
  onClearHistory(){
    this.setData({
      historyList: []
    })
    wx.setStorageSync('history', [])
  },

  //点击历史记录进行搜索
  onHistorySearch(e){
      console.log("点击历史记录进行搜索",e);
      let {historyValue} = e.currentTarget.dataset;
      this.setData({
        inputValue: historyValue
      })
      this.getGoodsList(historyValue);
  }
})